package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-04-12
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {

        //判断是否登录
        User user = MediaThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //判断参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //构建分页和查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getUserId, user.getUserId());


        //文章状态
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //类型
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //发布时间大于
        if (dto.getBeginPubDate() != null) {
            queryWrapper.gt(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        //发布时间小于
        if (dto.getEndPubDate() != null) {
            queryWrapper.lt(WmNews::getPublishTime, dto.getEndPubDate());
        }
        //关键字模糊查询
        if (dto.getKeyword() != null) {
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //倒序
        queryWrapper.orderByDesc(WmNews::getPublishTime);


        //构建分页条件
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> iPage = this.page(page, queryWrapper);

        //封装分页返回对象
        PageResponseResult<WmNews> result = new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
        return result;


    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {

        //是否登录
        User user = MediaThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否有id，是新增还是修改
        if (dto.getId() != null) {//修改，先删除旧表
            deleteRelation(dto.getId());
        }
        //没有id新增文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setImages(JSON.toJSONString(dto.getImages()));
        // 从前端传递的内容中提取图片
        List<ImageDto> contentImages = getImagesFromContent(wmNews.getContent());
        //封面是自动类型,只能从文章内容中的图片做为封面
        if (dto.getType() == -1) {
            // 需要从内容中自动提取图片作为封面图片
            if (contentImages != null) {
                // 判断内容图片的个数
                if (contentImages.size() <= 0) {
                    //设置为无封面
                    wmNews.setType(0);
                } else if (contentImages.size() < 3) {
                    //设置为单图
                    wmNews.setType(1);
                    List<ImageDto> imageList = contentImages.subList(0, 1);
                    wmNews.setImages(JSON.toJSONString(imageList));
                } else if (contentImages.size() >= 3) {
                    //设置为多图
                    wmNews.setType(3);
                    List<ImageDto> imageList = contentImages.subList(0, 3);
                    wmNews.setImages(JSON.toJSONString(imageList));
                }
            }
        }

        //保存文章
        this.saveOrUpdate(wmNews);
        //判断是否为草稿
        if (dto.getStatus() != 0) {

            //不是草稿，保存文章素材关联表 包含内容关联和封面关联
            //添加封面和素材图片的关联
            List<ImageDto> coverImages = JSON.parseArray(wmNews.getImages(), ImageDto.class);
            saveRelation(coverImages, wmNews.getId(), 1);
            //添加内容图片和素材图片的关系
            saveRelation(contentImages, wmNews.getId(), 0);

            //自动审核
            System.out.println(Thread.currentThread().getName() + "开始调用自动审核服务");
            auditService.audit(wmNews);


        }

        return ResponseResult.okResult();

    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.upDownTopic}")
    private String upDownTopic;
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {

        //根据id查找文章
        WmNews wmNews = this.getById(dto.getId());
        //判断文章是否为空
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //判断文章是否是更新状态
        if (wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //下架文章
        wmNews.setEnable(dto.getEnable() == 0 ? false : true);
        this.updateById(wmNews);

        //同步最新状态到APP端
        //发送消息的kafka
        kafkaTemplate.send(upDownTopic, wmNews.getArticleId().toString(), dto.getEnable() == 1 ? "true" : "false");

        return ResponseResult.okResult();

    }









    @Autowired
    @Lazy //懒加载防止循环引入
    private IAuditService auditService;

    /**
     * 从前端传递的内容中提取图片
     *
     * @param content
     * @return
     */
    private List<ImageDto> getImagesFromContent(String content) {

        ArrayList<ImageDto> imageDtoList = new ArrayList<>();
        //json内容转为数组
        List<ContentDto> dtos = JSON.parseArray(content, ContentDto.class);
        if (dtos != null) {
            for (ContentDto dto : dtos) {
                if (dto.getType().equals("image")) {
                    Integer newsId = dto.getId();
                    String url = dto.getValue();
                    ImageDto imageDto = new ImageDto(newsId, url);
                    imageDtoList.add(imageDto);

                }


            }

        }
        return imageDtoList;



    }
    /**
     * 保存关联关系
     *
     * @param images
     * @param newsId
     * @param type
     */
    private void saveRelation(List<ImageDto> images, Integer newsId, int type) {
        int ord = 0;
        if (images != null) {
            for (ImageDto image : images) {
                WmNewsMaterial entity = new WmNewsMaterial();
                entity.setMaterialId(image.getId());
                entity.setNewsId(newsId);
                entity.setType(type);
                entity.setOrd(ord);
                newsMaterialService.save(entity);
                ord++;
            }
        }
    }

    @Autowired
    private IWmNewsMaterialService newsMaterialService;

    /**
     * 删除文章-素材关联
     *
     * @param id
     */
    private void deleteRelation(Integer id) {

        //根据文章id删除关联表
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId, id);
        newsMaterialService.remove(queryWrapper);

    }
}
